<template>
<!--  div.update-->
  <div class="image" v-if="imgUrl">
    <img :src="imgUrl" alt="">
    <i class="el-icon-error back" style="color: red;font-size: 25px" @click="clearImage"></i>
  </div>
  <el-upload drag :action="host" :data="dataObj"
             :before-upload="beforeUpload"
             :on-success="handleUploadSuccess"
             v-else
             style="display:inline">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
  </el-upload>
</template>

<script>
import {inject, watch, reactive, toRefs, ref} from "vue";
import {ElMessage} from 'element-plus';
import admin from "../request/api/aliCloud";

export default {
  name: "imgUpdate",
  props:["url"],
  setup(props, context) {
    const data = reactive({
      imgUrl: props.url,
      host: "https://bwinborn.oss-cn-shanghai.aliyuncs.com",
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
      },
    })
    const $http = inject("$http")

    const beforeUpload = (file) => {
      return new Promise((resolve, reject) => {
        $http.aliCloud.getOss().then(res => {
          data.dataObj.policy = res.result.policy
          data.dataObj.signature = res.result.signature
          data.dataObj.ossaccessKeyId = res.result.accessid
          data.dataObj.dir = res.result.dir
          // data.dataObj.host = res.result.host
          data.dataObj.key = res.result.dir + file.name
          resolve(true);
        })
      })
    }
    const handleUploadSuccess = () => {
      let url = data.host + "/" + data.dataObj.key
      data.imgUrl = url
      context.emit('successUpdate', url)
      ElMessage.success("文件上传成功")
    }
    const clearImage = () => {
      data.imgUrl = ""
    }
    watch(props, (newProps, oldProps) => {
      data.imgUrl = newProps.url
    });
    return {
      ...toRefs(data),
      beforeUpload,
      handleUploadSuccess,
      clearImage
    }
  }
}
</script>

<style scoped lang="less">
.image {
  position: relative;
  img {
    width: 150px;
    height: 120px;
  }
  .back {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9;
    cursor: pointer;
    &:hover {
      color: #ff046f !important;
    }
  }
}
</style>